package cn.com.inossem.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.util.Base64;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import Decoder.BASE64Encoder;
import cn.com.inossem.chat.ChatMsgEntity;
import cn.com.inossem.chat.ChatMsgViewAdapter;
import cn.com.inossem.config.WSConfig;
import cn.com.inossem.utils.Utils;
import io.socket.client.IO;
import io.socket.client.Socket;
import io.socket.emitter.Emitter;

/**
 * @author way
 */
public class FriendChatActivity extends Activity implements OnClickListener {

	private Button mBtnPic;
	private Button mBtnSend;// 发送btn
	private Button mBtnBack;// 返回btn
	private EditText mEditTextContent;
	private ListView mListView;
	private ChatMsgViewAdapter mAdapter;// 消息视图的Adapter
	private List<ChatMsgEntity> mDataArrays = new ArrayList<ChatMsgEntity>();// 消息对象数组

	String toUserId;
	String toUserName;
	String toUserHeader;

	String fromUserId;
	String fromUserName;
	String fromUserHeader;

	static Socket socket;

	String currentId = "";

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (socket != null && !socket.connected()) {
			socket.connect();
		}
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chat);

		fromUserId = Utils.messageInfo.userInfo.getId() + "";
		fromUserName = Utils.messageInfo.userInfo.getNickname() + "";
		fromUserHeader = Utils.messageInfo.userInfo.getImageData();

		toUserId = getIntent().getStringExtra("toUser");
		toUserName = getIntent().getStringExtra("toUserName");
		toUserHeader = getIntent().getStringExtra("toUserHeader");
		try {
			socket = IO.socket(WSConfig.LOCALURL);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		if (socket != null) {
			socket.on("connect", new Emitter.Listener() {
				@Override
				public void call(Object... arg0) {
					// TODO Auto-generated method stub
					// JSONObject obj = new JSONObject();
					JSONObject obj = null;
					// obj.addProperty("user", value)
					String jsonStr = "{\"user\":\""
							+ Utils.messageInfo.userInfo.getId() + "\"}";
					try {
						obj = new JSONObject(jsonStr);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

					socket.emit("connectedUser", obj);

				}
			});

			socket.on("privateMessage", new Emitter.Listener() {

				@Override
				public void call(Object... arg0) {
					// TODO Auto-generated method stub
					if (arg0 != null && arg0.length > 0) {
						JSONObject jsonObj = (JSONObject) arg0[0];
						MessageEntity msg = new MessageEntity();// gson.fromJson(jsonObj.toString(),
						// MessageEntity.class);
						try {
							msg.created = jsonObj.getString("created");
							msg.text = jsonObj.getString("text");
							msg.fromUser = jsonObj.getString("fromUser");
							msg.toUser = jsonObj.getString("toUser");
							msg.flag = "1".equals(jsonObj.getString("type"));

						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}

						Message message = new Message();
						message.obj = msg;
						message.what = 0;
						handler.sendMessage(message);
						// showMessage(msg);
					}
				}
			});

			socket.connect();
		}

		initView();// 初始化view

		mAdapter = new ChatMsgViewAdapter(this, mDataArrays);
		mListView.setAdapter(mAdapter);

		getData("");

		initScrollListener();
	}

	private void initScrollListener() {
		mListView.setOnScrollListener(new OnScrollListener() {
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
					if (view.getFirstVisiblePosition() == 0) {
						loadMore();
					}
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
			                     int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub

			}
		});
	}

	private boolean loadMoreFlag = false;

	public void loadMore() {
		if (!loadMoreFlag) {
			loadMoreFlag = true;
			System.out.println("get more!!!");
			getData(currentId == null ? "" : currentId);
			// List<ChatMsgEntity> resultList = getData();
			// if (resultList != null && !resultList.isEmpty()) {
			// mDataArrays.addAll(resultList);
			// mAdapter.notifyDataSetChanged();
			// }
		}
	}

	/**
	 * 初始化view
	 */
	public void initView() {
		mListView = (ListView) findViewById(R.id.listview);
		mBtnSend = (Button) findViewById(R.id.btn_send);
		mBtnSend.setOnClickListener(this);
		mBtnBack = (Button) findViewById(R.id.btn_back);
		mBtnBack.setOnClickListener(this);
		mBtnPic = (Button) findViewById(R.id.btn_pic);
		mBtnPic.setOnClickListener(this);
		mEditTextContent = (EditText) findViewById(R.id.et_sendmessage);
	}

	private final static int COUNT = 12;// 初始化数组总数

	/**
	 * 模拟加载消息历史，实际开发可以从数据库中读出
	 */
	public void initData(List<ChatMsgEntity> resultList) {
		if (resultList != null && !resultList.isEmpty()) {
			mDataArrays.clear();
			mDataArrays.addAll(resultList);
			mAdapter.notifyDataSetChanged();
			mListView.setSelection(mAdapter.getCount() - 1);
		}
	}

	public void loadMoreData(List<ChatMsgEntity> resultList) {
		if (resultList != null && !resultList.isEmpty()) {
			currentId = resultList.get(0).getId();
			resultList.addAll(mDataArrays);
			mDataArrays.clear();
			for (ChatMsgEntity msg : resultList) {
				mDataArrays.add(msg);
			}
			mAdapter.notifyDataSetChanged();
			loadMoreFlag = false;
		}
	}

	private Handler handler_loadData = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			String jsonStr = (String) msg.obj;
			initData(getResultList(jsonStr));
		}
	};

	private Handler handler_loadMoreData = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			String jsonStr = (String) msg.obj;
			loadMoreData(getResultList(jsonStr));
		}
	};

	private void getData(final String id) {
		final HttpGet httpGet = new HttpGet(WSConfig.LOCALURL
				+ "/api/chatboxes/" + toUserId + "?user=" + fromUserId
				+ "&chat=" + (id == null ? "" : id));
		new Thread(new Runnable() {
			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					final HttpResponse httpResponse = new DefaultHttpClient().execute(httpGet);
					String result = "";
					if (httpResponse.getStatusLine().getStatusCode() == 200) {
						HttpEntity entity = httpResponse.getEntity();
						try {
							result = EntityUtils.toString(entity);
						} catch (Exception e) {
							e.printStackTrace();
						}
						result.replaceAll("\r", "");
					}
					Message msg = new Message();
					msg.obj = result;
					if (result != null && !result.isEmpty()) {
						if (id != null && !id.isEmpty()) {
							handler_loadMoreData.sendMessage(msg);
						} else {
							handler_loadData.sendMessage(msg);
						}
					}

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	private List<ChatMsgEntity> getResultList(String jsonStr) {
		List<ChatMsgEntity> resultList = new ArrayList<ChatMsgEntity>();
		JSONArray array = null;
		try {
			array = new JSONArray(jsonStr);
		} catch (Exception e) {
			e.printStackTrace();
		}

		for (int i = 0; i < array.length(); i++) {
			try {
				JSONObject obj = array.getJSONObject(i);
				ChatMsgEntity entity = new ChatMsgEntity();
				entity.setId(obj.getString("id"));

				if (i == 0) {
					currentId = entity.getId();
				}

				entity.setDate(obj.getString("created"));
				entity.setImg("1".equals(obj.getString("type")));
				String fromId = obj.getString("fromUser");
				if (fromUserId.equals(fromId)) {
					entity.setName(Utils.messageInfo.userInfo.getNickname());
					entity.setHeader(fromUserHeader);
				} else {
					entity.setName(toUserName);
					entity.setHeader(toUserHeader);
				}
				if ("0".equals(obj.getString("fromMe"))) {
					entity.setMsgType(true);
				} else {
					entity.setMsgType(false);
				}
				entity.setMessage(obj.getString("text"));
				resultList.add(entity);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return resultList;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.btn_pic:
				showDialog(COMMON_DIALOG);
			case R.id.btn_send:// 发送按钮点击事件
				send(mEditTextContent.getText().toString(), false);
				break;
			case R.id.btn_back:// 返回按钮点击事件
				socket.disconnect();
				finish();// 结束,实际开发中，可以返回主界面
				break;
		}
	}

	/**
	 * 发送消息
	 */
	private void send(String text, Boolean isImg) {
		// String contString = mEditTextContent.getText().toString();
		if (text.length() > 0) {
			ChatMsgEntity entity = new ChatMsgEntity();
			entity.setName(fromUserName);
			entity.setDate(getDate());
			entity.setMessage(text);
			entity.setMsgType(false);
			entity.setImg(isImg);
			mDataArrays.add(entity);
			mAdapter.notifyDataSetChanged();// 通知ListView，数据已发生改变

			mEditTextContent.setText("");// 清空编辑框数据

			((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
					.hideSoftInputFromWindow(
							getCurrentFocus().getWindowToken(),
							InputMethodManager.HIDE_NOT_ALWAYS);

			mListView.setSelection(mListView.getCount() - 1);// 发送一条消息时，ListView显示选择最后一项
			sendSocket(text, isImg);
		}
	}

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			showMessage((MessageEntity) msg.obj);
		}
	};

	private void showMessage(MessageEntity me) {
		ChatMsgEntity entity = new ChatMsgEntity();
		entity.setName("1".equals(me.fromMe) ? fromUserName : toUserName);
		entity.setDate(me.created);
		entity.setMessage(me.text);
		entity.setMsgType("1".equals(me.fromMe) ? false : true);
		entity.setImg(me.flag);
		mDataArrays.add(entity);
		mAdapter.notifyDataSetChanged();// 通知ListView，数据已发生改变

		mEditTextContent.setText("");// 清空编辑框数据

		mListView.setSelection(mListView.getCount() - 1);// 发送一条消息时，ListView显示选择最后一项
	}

	public void sendSocket(String text, boolean flag) {
		MessageEntity me = new MessageEntity();
		me.text = text;
		me.fromUser = fromUserId;
		me.toUser = toUserId;
		me.type = flag ? "1" : "0";
		Gson gson = new Gson();
		String jsonStr = gson.toJson(me, MessageEntity.class);
		JSONObject jsonObj = null;
		try {
			jsonObj = new JSONObject(jsonStr);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (socket != null && socket.connected()) {
			socket.emit("privateMessage", jsonObj);
		}
	}

	/**
	 * 发送消息时，获取当前事件
	 *
	 * @return 当前时间
	 */
	@SuppressLint("SimpleDateFormat")
	private String getDate() {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		return format.format(new Date());
	}

	public class MessageEntity {
		public String type;
		public String text;
		public String fromUser;
		public String toUser;
		public String created;
		public String chatId;
		public String fromMe;
		public boolean flag;
	}

	// ------------- ---------------

	final int COMMON_DIALOG = 1;

	protected Dialog onCreateDialog(int id) { // 重写onCreateDialog方法
		Dialog dialog = null; // 声明一个Dialog对象用于返回
		switch (id) { // 对id进行判断
			case COMMON_DIALOG:
				Builder b = new AlertDialog.Builder(this);
				// b.setIcon(); //设置对话框的图标
				b.setTitle(R.string.dialogTitle); // 设置对话框的标题
				b.setMessage(R.string.fangshi); // 设置对话框的显示内容
				b.setPositiveButton( // 添加按钮
						R.string.xiangce, new DialogInterface.OnClickListener() { // 为按钮添加监听器
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								setViewChocie();
							}
						});
				b.setNegativeButton( // 添加按钮
						R.string.paiyizhang, new DialogInterface.OnClickListener() { // 为按钮添加监听器
							public void onClick(DialogInterface dialog, int which) {
								// TODO Auto-generated method stub
								setPaizhaoChocie();
							}
						});
				dialog = b.create(); // 生成Dialog对象
				break;
			default:
				break;
		}
		return dialog; // 返回生成Dialog的对象
	}

	private void setViewChocie() {
		// Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		// intent.addCategory(Intent.CATEGORY_OPENABLE);
		// intent.setType("image/*");
		// intent.putExtra("return-data", true);
		//
		// startActivityForResult(intent, 0);

		// Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		// intent.setType("image/*");
		// startActivityForResult(intent, 0);

		// Intent i = new Intent(Intent.ACTION_PICK,
		// android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		//
		// startActivityForResult(i, 0);

		// Intent intent = new Intent();
		// intent.setType("image/*");
		// intent.setAction(Intent.ACTION_GET_CONTENT);
		// startActivityForResult(intent, 0);

		Intent intent = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
				"image/*");
		startActivityForResult(intent, 0);

	}

	private void setPaizhaoChocie() {
		// String state = Environment.getExternalStorageState();
		// if (state.equals(Environment.MEDIA_MOUNTED)) {
		// Intent getImageByCamera = new Intent(
		// "android.media.action.IMAGE_CAPTURE");
		// startActivityForResult(getImageByCamera, CAMERA_WITH_DATA);
		// } else {
		// Toast.makeText(getApplicationContext(), "请确认已经插入SD卡",
		// Toast.LENGTH_LONG).show();
		// }

		String status = Environment.getExternalStorageState();
		if (status.equals(Environment.MEDIA_MOUNTED)) {
			try {
				File dir = new File(Environment.getExternalStorageDirectory()
						+ "/" + "sapapp");
				if (!dir.exists())
					dir.mkdirs();

				Intent intent = new Intent(
						android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
				File f = new File(dir, "paizhao.jpg");// localTempImgDir和localTempImageFileName是自己定义的名字
				Uri u = Uri.fromFile(f);
				intent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
				intent.putExtra(MediaStore.EXTRA_OUTPUT, u);
				startActivityForResult(intent, CAMERA_WITH_DATA);
			} catch (ActivityNotFoundException e) {
				// TODO Auto-generated catch block
				Toast.makeText(this, "没有找到储存目录", Toast.LENGTH_LONG).show();
			}
		} else {
			Toast.makeText(this, "没有储存卡", Toast.LENGTH_LONG).show();
		}
	}

	BitmapDrawable drawable;
	Bitmap cameraBitmap;
	private static final int PHOTO_PICKED_WITH_DATA = 3021;
	private static final int CAMERA_WITH_DATA = 3023;

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		if (resultCode != -1)
			return;
		cameraBitmap = null;
		System.out.println(requestCode + "resultCode:" + resultCode);

		switch (requestCode) {
			case 0:

				Uri originalUri = data.getData();
				if (originalUri != null) {
					// cameraBitmap =
					// MediaStore.Images.Media.getBitmap(resolver,
					// originalUri);
					String[] filePathColumn = {MediaStore.Images.Media.DATA};

					Cursor cursor = getContentResolver().query(originalUri,
							filePathColumn, null, null, null);
					cursor.moveToFirst();
					int column_index = cursor.getColumnIndex(filePathColumn[0]);
					String picturePath = cursor.getString(column_index);
					cursor.close();
					cameraBitmap = comp(BitmapFactory.decodeFile(picturePath));
					String imagestr = bitmaptoString(cameraBitmap);
					Bitmap bit = stringtoBitmap(imagestr);

					addpic(imagestr, bit);
				}
				// cameraBitmap = (Bitmap) data.getExtras().get("data");
				// if (cameraBitmap != null) {
				// // String imagestr = bitmaptoString(cameraBitmap);
				// addpic("", cameraBitmap);
				// // Utils.messageInfo.userInfo.setImageData(imagestr);
				// // touxiang.setBackgroundDrawable(new BitmapDrawable(Utils
				// // .toRoundCorner(cameraBitmap, 50)));
				// }
				break;
			case CAMERA_WITH_DATA:
				// final Bitmap photo = data.getParcelableExtra("data");
				// cameraBitmap = photo;
				// String imagestr = bitmaptoString(cameraBitmap);
				// Bitmap bit = stringtoBitmap(imagestr);
				// addpic(imagestr, bit);
				// if (data != null) {
				// // 取得返回的Uri,基本上选择照片的时候返回的是以Uri形式，但是在拍照中有得机子呢Uri是空的，所以要特别注意
				// Uri mImageCaptureUri = data.getData();
				// // 返回的Uri不为空时，那么图片信息数据都会在Uri中获得。如果为空，那么我们就进行下面的方式获取
				// if (mImageCaptureUri != null) {
				// Bitmap image;
				// try {
				// // 这个方法是根据Uri获取Bitmap图片的静态方法
				// image = MediaStore.Images.Media.getBitmap(
				// this.getContentResolver(), mImageCaptureUri);
				// if (image != null) {
				// savePicToSdcard(image, "/sdcard/sapapp/",
				// "paizhao.jpg");
				//
				// image = rotaingImageView(
				// readPictureDegree("/sdcard/sapapp/paizhao.jpg"),
				// image);
				// String imagestr = bitmaptoString(image);
				// Bitmap bit = stringtoBitmap(imagestr);
				// addpic(imagestr, bit);
				// }
				// } catch (Exception e) {
				// e.printStackTrace();
				// }
				// } else {
				// Bundle extras = data.getExtras();
				// if (extras != null) {
				// // 这里是有些拍照后的图片是直接存放到Bundle中的所以我们可以从这里面获取Bitmap图片
				// Bitmap image = extras.getParcelable("data");
				// if (image != null) {
				// savePicToSdcard(image, "/sdcard/sapapp/",
				// "paizhao.jpg");
				// image = rotaingImageView(
				// readPictureDegree("/sdcard/sapapp/paizhao.jpg"),
				// image);
				// String imagestr = bitmaptoString(image);
				// Bitmap bit = stringtoBitmap(imagestr);
				// addpic(imagestr, bit);
				// }
				// }
				// }
				//
				// }

				File f = new File(Environment.getExternalStorageDirectory() + "/"
						+ "sapapp" + "/" + "paizhao.jpg");
				try {
					Uri u = Uri.parse(android.provider.MediaStore.Images.Media
							.insertImage(getContentResolver(), f.getAbsolutePath(),
									null, null));
					String[] filePathColumn = {MediaStore.Images.Media.DATA};

					Cursor cursor = getContentResolver().query(u, filePathColumn,
							null, null, null);
					cursor.moveToFirst();
					int column_index = cursor.getColumnIndex(filePathColumn[0]);
					String picturePath = cursor.getString(column_index);
					cursor.close();
					cameraBitmap = ratio(BitmapFactory.decodeFile(picturePath),
							300, 300);
					String imagestr = bitmaptoString(cameraBitmap);
					addpic(imagestr, cameraBitmap);
					// u就是拍摄获得的原始图片的uri，剩下的你想干神马坏事请便……
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				break;
			case PHOTO_PICKED_WITH_DATA:
				cameraBitmap = data.getParcelableExtra("data");
				if (cameraBitmap != null) {
					// imagestr = bitmaptoString(cameraBitmap);
					// Utils.messageInfo.userInfo.setImageData(imagestr);

					// touxiang.setBackgroundDrawable(new BitmapDrawable(Utils
					// .toRoundCorner(cameraBitmap, 50)));
				}
				break;

			default:
				break;
		}
	}

	/**
	 * Compress image by size, this will modify image width/height. Used to get
	 * thumbnail
	 *
	 * @param image
	 * @param pixelW target pixel of width
	 * @param pixelH target pixel of height
	 * @return
	 */
	public Bitmap ratio(Bitmap image, float pixelW, float pixelH) {
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 100, os);
		if (os.toByteArray().length / 1024 > 1024) {// 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
			os.reset();// 重置baos即清空baos
			image.compress(Bitmap.CompressFormat.JPEG, 50, os);// 这里压缩50%，把压缩后的数据存放到baos中
		}
		ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		newOpts.inPreferredConfig = Config.RGB_565;
		Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		float hh = pixelH;// 设置高度为240f时，可以明显看到图片缩小了
		float ww = pixelW;// 设置宽度为120f，可以明显看到图片缩小了
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;// be=1表示不缩放
		if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置缩放比例
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		is = new ByteArrayInputStream(os.toByteArray());
		bitmap = BitmapFactory.decodeStream(is, null, newOpts);
		// 压缩好比例大小后再进行质量压缩
		// return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大，反而耗资源，删除
		return bitmap;
	}

	/**
	 * 读取图片属性：旋转的角度
	 *
	 * @param path 图片绝对路径
	 * @return degree旋转的角度
	 */
	public static int readPictureDegree(String path) {
		int degree = 0;
		try {
			ExifInterface exifInterface = new ExifInterface(path);
			int orientation = exifInterface.getAttributeInt(
					ExifInterface.TAG_ORIENTATION,
					ExifInterface.ORIENTATION_NORMAL);
			switch (orientation) {
				case ExifInterface.ORIENTATION_ROTATE_90:
					degree = 90;
					break;
				case ExifInterface.ORIENTATION_ROTATE_180:
					degree = 180;
					break;
				case ExifInterface.ORIENTATION_ROTATE_270:
					degree = 270;
					break;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return degree;
	}

	/*
	 * 旋转图片
	 * 
	 * @param angle
	 * 
	 * @param bitmap
	 * 
	 * @return Bitmap
	 */
	public static Bitmap rotaingImageView(int angle, Bitmap bitmap) {
		// 旋转图片 动作
		Matrix matrix = new Matrix();
		matrix.postRotate(angle);
		System.out.println("angle2=" + angle);
		// 创建新的图片
		Bitmap resizedBitmap = Bitmap.createBitmap(bitmap, 0, 0,
				bitmap.getWidth(), bitmap.getHeight(), matrix, true);
		return resizedBitmap;
	}

	public static String savePicToSdcard(Bitmap bitmap, String path,
	                                     String fileName) {
		String filePath = "";
		if (bitmap == null) {
			return filePath;
		} else {

			filePath = path + fileName;
			File destFile = new File(filePath);
			OutputStream os = null;
			try {
				os = new FileOutputStream(destFile);
				bitmap.compress(CompressFormat.JPEG, 100, os);
				os.flush();
				os.close();
			} catch (IOException e) {
				filePath = "";
			}
		}
		return filePath;
	}

	public String bitmaptoString(Bitmap bitmap) {
		// 将Bitmap转换成字符串
		String string = null;
		ByteArrayOutputStream bStream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.JPEG, 100, bStream);
		byte[] bytes = bStream.toByteArray();
		string = Base64.encodeToString(bytes, Base64.DEFAULT);
		return string;
	}

	public Bitmap stringtoBitmap(String string) {
		// 将字符串转换成Bitmap类型
		Bitmap bitmap = null;
		try {
			byte[] bitmapArray;
			bitmapArray = Base64.decode(string, Base64.DEFAULT);
			bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
					bitmapArray.length);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return bitmap;
	}

	/**
	 * bitmap转为base64
	 *
	 * @param bitmap
	 * @return
	 */
	public static String bitmapToBase64(Bitmap bitmap) {

		String result = null;
		ByteArrayOutputStream baos = null;
		try {
			if (bitmap != null) {
				baos = new ByteArrayOutputStream();
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

				baos.flush();
				baos.close();

				byte[] bitmapBytes = baos.toByteArray();
				result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (baos != null) {
					baos.flush();
					baos.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * base64转为bitmap
	 *
	 * @param base64Data
	 * @return
	 */
	public static Bitmap base64ToBitmap(String base64Data) {
		byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
		return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
	}

	protected void doCropPhoto(Bitmap data) {
		Intent intent = getCropImageIntent(data);
		startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
	}

	public static Intent getCropImageIntent(Bitmap data) {
		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
		intent.setType("image/*");
		intent.putExtra("data", data);
		// intent.putExtra("crop", "true");
		// intent.putExtra("aspectX", 1);
		// intent.putExtra("aspectY", 1);
		// intent.putExtra("outputX", 80);
		// intent.putExtra("outputY", 80);
		intent.putExtra("return-data", true);
		return intent;
	}

	private Bitmap comp(Bitmap image) {

		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 10, baos);
		// if (baos.toByteArray().length / 1024 > 300) {//
		// 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
		// baos.reset();// 重置baos即清空baos
		// image.compress(Bitmap.CompressFormat.JPEG, 80, baos);//
		// 这里压缩50%，把压缩后的数据存放到baos中
		// }
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());
		BitmapFactory.Options newOpts = new BitmapFactory.Options();
		// 开始读入图片，此时把options.inJustDecodeBounds 设回true了
		newOpts.inJustDecodeBounds = true;
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		newOpts.inJustDecodeBounds = false;
		int w = newOpts.outWidth;
		int h = newOpts.outHeight;
		// 现在主流手机比较多是800*480分辨率，所以高和宽我们设置为
		float hh = 800f;// 这里设置高度为800f
		float ww = 480f;// 这里设置宽度为480f
		// 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
		int be = 1;// be=1表示不缩放
		if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
			be = (int) (newOpts.outWidth / ww);
		} else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
			be = (int) (newOpts.outHeight / hh);
		}
		if (be <= 0)
			be = 1;
		newOpts.inSampleSize = be;// 设置缩放比例
		newOpts.inPreferredConfig = Config.RGB_565;// 降低图片从ARGB888到RGB565
		// 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
		isBm = new ByteArrayInputStream(baos.toByteArray());
		bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
		return compressImage(bitmap);// 压缩好比例大小后再进行质量压缩
	}

	private Bitmap compressImage(Bitmap image) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		image.compress(Bitmap.CompressFormat.JPEG, 20, baos);// 质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
		// int options = 100;
		// while (baos.toByteArray().length / 1024 > 300) { //
		// 循环判断如果压缩后图片是否大于100kb,大于继续压缩
		// baos.reset();// 重置baos即清空baos
		// options -= 10;// 每次都减少10
		// image.compress(Bitmap.CompressFormat.JPEG, options, baos);//
		// 这里压缩options%，把压缩后的数据存放到baos中
		//
		// }
		ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
		Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片
		return bitmap;
	}

	String name;
	String picname;

	private void getInfo() {
		SharedPreferences settings = this
				.getSharedPreferences("shared_file", 0);
		// 第二个参数为如果SharedPreferences中没有保存就赋一个默认值
		name = settings.getString("name", "许愿的猪");
		picname = settings.getString("picname", "h1");
	}

	// 图片转化成base64字符串
	public static String GetImageStr(String imgFile) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
		InputStream in = null;
		byte[] data = null;
		// 读取图片字节数组
		try {
			in = new FileInputStream(imgFile);
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 对字节数组Base64编码
		BASE64Encoder encoder = new BASE64Encoder();
		return encoder.encode(data);// 返回Base64编码过的字节数组字符串
	}

	List<String> piclist = new ArrayList<String>();

	public void addpic(final String str, Bitmap bitmap) {
		piclist.add(str);
		ImageView img = new ImageView(this);
		img.setLayoutParams(new LayoutParams(Utils.dip2px(this, 80), Utils
				.dip2px(this, 80)));
		// img.setBackgroundDrawable(new BitmapDrawable(stringtoBitmap(str)));
		img.setBackgroundDrawable(new BitmapDrawable(bitmap));
		// img.setImageBitmap(bitmap);
		send(bitmaptoString(bitmap), true);
		img.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				// piclist.remove(str);
				System.out.println("piclist.size():" + piclist.size());
				// piclayout.removeView(arg0);

			}
		});
	}
}